var express = require('express');
var router = express.Router();

/* GET home page. */
router
	.get('/', function(req, res, next) {
		res.render("login");
	})
	.post('/', function(req, res, next) {

		var response;

		var mysql      = require('mysql');
		var connection = mysql.createConnection({
							    host     : 'localhost',
							    user     : 'root',
							    password : 'root',
							    database : 'jingsai'
							});

		connection.connect();

		connection.query('SELECT USERNAME, PASSWORD FROM USERS ' +
		    "WHERE USERNAME='"+req.body.username+"'", function (error, data) {
		    if (error) throw error;
		    if(data.length>0 && data[0].PASSWORD==req.body.password){
				response = {
					"status":"success"
				}
				req.session.user = "admin";
				console.log(req.body.username + " loging success!");
		    }else{
				response = {
					"status":"failed"
				}
				console.log(req.body.username + " loging failed!");		    	
		    }
			
			res.json(response);
		  });


	});

module.exports = router;
